# PowerShell script to add a specified path to the PATH environment variable
# Run this script with administrator privileges

param (
    [Parameter(Mandatory=$true)]
    [string]$PathToAdd,
    
    [Parameter(Mandatory=$false)]
    [ValidateSet("User", "System")]
    [string]$Target = "User"
)

# Check if running with administrator privileges
function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
    return $currentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

# Administrator privileges required for system variables
if ($Target -eq "System" -and -not (Test-Admin)) {
    Write-Error "Administrator privileges required to modify system environment variables. Please restart this script as Administrator."
    exit 1
}

# Ensure the path exists
if (-not (Test-Path $PathToAdd)) {
    Write-Warning "The specified path '$PathToAdd' does not exist. Continue? (Y/N)"
    $response = Read-Host
    if ($response -ne "Y" -and $response -ne "y") {
        Write-Output "Operation cancelled."
        exit 0
    }
}

# Get current PATH environment variable
if ($Target -eq "User") {
    $currentPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::User)
} else {
    $currentPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine)
}

# Check if path already exists in the environment variable
$pathArray = $currentPath -split ";"
if ($pathArray -contains $PathToAdd) {
    Write-Output "The path '$PathToAdd' already exists in the $Target PATH environment variable."
    exit 0
}

# Add the new path
$newPath = $currentPath
if ($newPath.EndsWith(";")) {
    $newPath = $newPath + $PathToAdd
} else {
    $newPath = $newPath + ";" + $PathToAdd
}

# Update the environment variable
try {
    if ($Target -eq "User") {
        [Environment]::SetEnvironmentVariable("Path", $newPath, [EnvironmentVariableTarget]::User)
    } else {
        [Environment]::SetEnvironmentVariable("Path", $newPath, [EnvironmentVariableTarget]::Machine)
    }
    Write-Output "Successfully added '$PathToAdd' to the $Target PATH environment variable."
    Write-Output "Please restart PowerShell or open a new command window for the changes to take effect."
} catch {
    Write-Error "Unable to update environment variable: $_"
    exit 1
} 